//
//  VIPTipViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/16.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import PKHUD

class VIPTipViewController: BaseViewController {

  enum BecomeVIPActionType {
    case login, buyVIP
  }
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var webView: UIWebView!
  @IBOutlet private weak var topViewTopConstraint: NSLayoutConstraint!
  @IBOutlet private weak var reloadButton: UIButton!
  @IBOutlet private weak var becomVIPButton: UIButton!
  
  // MARK: - Private vars
  
  private var becomeVIPActionType: BecomeVIPActionType = .login
  
  // MARK: - Private methods
  
  private func prepareUI() {
    webView.scrollView.delegate = self
    webView.alpha = 0
    reloadButton.alpha = 0
    
    resetButtonState()
  }
  
  @objc private func resetButtonState() {
    if let _ = UserManager.shared.currentUser {
      becomeVIPActionType = .buyVIP
      becomVIPButton.setTitle("成为会员", for: .normal)
    } else {
      becomeVIPActionType = .login
      becomVIPButton.setTitle("用户登录", for: .normal)
    }
  }
  
  private func loadContent() {
    if let url = URL(string: APIURLStrings.vipTipHTML) {
      let request = URLRequest(url: url)
      
      UIView.animate(withDuration: 0.3, animations: {
        self.webView.alpha = 0
        self.reloadButton.alpha = 0
      }) { _ in
        self.webView.loadRequest(request)
      }
    }
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    prefersLargeTitles = true
    
    NotificationCenter.default.addObserver(self, selector: #selector(resetButtonState), name: .currentUserUpdated, object: nil)
    
    prepareUI()
    loadContent()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
   
  deinit {
    NotificationCenter.default.removeObserver(self)
  }
  
  // MARK: - IBActions
  
  @IBAction func reload() {
    loadContent()
  }
  
  @IBAction func becomeVIPButtonTapped() {
    switch becomeVIPActionType {
    case .login: //用户登录
      let loginViewController = UIStoryboard(name: "Account", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
      loginViewController.addCloseButton()
      let nav = BaseNavigationController(rootViewController: loginViewController, dismissDelegate: self)
      nav.isPresentedModally = true
      self.present(nav, animated: true)
    case .buyVIP: //成为会员
        let alert = UIAlertController.init(title: "确认是否成为会员", message: nil, cancelTitle: "取消", cancelHandler: nil, confirmTitle: "确认") { (_) in
            //检查用户代币余额是否足够购买会员
            API.shared.requestAPI (APIURLStrings.allTokens,method: .get,header: API.shared.memeberHeader,successCallback: { json in
                
                let myTotalCoins = json["my_total_coins"].intValue
                if let coinListJsons = json["coins"].array {
                    let vipCoinsInfo = coinListJsons.last!
                    let vipNeedCoins = vipCoinsInfo["count"].intValue //列单最后一栏为vip费用
                    if myTotalCoins >= vipNeedCoins {//金额充足
                        
                        let body = ["type" : 2]
                        API.shared.requestAPI (APIURLStrings.exchangeContent,method: .post,body: body,header: API.shared.memeberHeader,successCallback: { json in
                            
                            HUD.flash(.labeledSuccess(title: "兑换成功", subtitle: nil), delay: 1.5)
                            if var currentUser = UserManager.shared.currentUser {
                              currentUser.isPremium = true
                              currentUser.hadBeenPremium = true
                              UserManager.shared.currentUser = currentUser
                              DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                                NotificationCenter.default.post(name: .currentUserUpdated, object: nil)
                              }
                            }
                        }, errorCallback: { (message, code) in
                            HUD.flash(.labeledError(title: "兑换失败", subtitle: message), delay: 1.5)
                        })
                        
                    }
                    else {//金额不充足
                        
                        let alert = UIAlertController.init(title: "余额不足", message: "尊敬的用户你的狮羊曼尼不足\(vipNeedCoins)，请先充值", cancelTitle: "取消", cancelHandler: nil, confirmTitle: "充值") {_ in
                            let controller = UIStoryboard(name: "Account", bundle: nil).instantiateViewController(withIdentifier: "TokenViewController")
                            self.navigationController?.pushViewController(controller, animated: true)
                        }
                        self.present(alert, animated: true, completion: nil)
                    }
                }
                
            }) { (message, code) in
                HUD.flash(.labeledError(title: "请求失败", subtitle: "请重试"), delay: 1.5)
            }
        }
        self.present(alert, animated: true, completion: nil)
    }
  }
  
  @IBAction func showPlayHistory(_ sender: UIBarButtonItem) {
    if let playHistoryNavigationController = UIStoryboard(name: "Player", bundle: nil).instantiateViewController(withIdentifier: "PlayHistoryNavigationController") as? BaseNavigationController {
      playHistoryNavigationController.dismissDelegate = self
      present(playHistoryNavigationController, animated: true)
    }
  }
}

// MARK: - UIWebViewDelegate

extension VIPTipViewController: UIWebViewDelegate {
  func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
    UIView.animate(withDuration: 0.3) {
      self.webView.alpha = 0
      self.reloadButton.alpha = 1
    }
  }
  
  func webViewDidFinishLoad(_ webView: UIWebView) {
    UIView.animate(withDuration: 0.3) {
      self.webView.alpha = 1
      self.reloadButton.alpha = 0
    }
  }
}

// MARK: - UIScrollViewDelegate

extension VIPTipViewController: UIScrollViewDelegate {
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if #available(iOS 11.0, *) {
      // re-position category view
      let delta = 96 + UIApplication.shared.statusBarFrame.height // 96 is height of large title navbar
      if scrollView.contentOffset.y <= -delta {
        topViewTopConstraint.constant = -delta - scrollView.contentOffset.y
      } else {
        topViewTopConstraint.constant = 0
      }
    }
  }
}

// MARK: - BaseNavigationControllerDismissDelegate

extension VIPTipViewController: BaseNavigationControllerDismissDelegate {
  func dismiss(navigationController: BaseNavigationController, completion: (() -> Void)?) {
    dismiss(animated: true, completion: completion)
  }
}

